<template>
	<ppl-navbar title="校园生活" bgColor="#3c91ff" titleColor="#FFFFFF">
		<view class="nav-left position-icon" @click="selectSchool">
			<view class="location-icon-wrapper">
				<van-icon size="24rpx" color="#FFFFFF" name="location" />
			</view>
			<view class="school-name-container">
				<view class="school-name text-ellipsis">
					{{schoolName}}
				</view>
			</view>
		</view>
	</ppl-navbar>

	<!-- 顶部装饰背景（不影响布局） -->
	<view class="decorative-bg" />

	<view class="page-wrapper">
		<!-- 公告栏和图片的组合容器 -->
		<view class="notice-and-image-container">
			<view class="notice-bar-wrapper flex-1">
				<view class="custom-notice-bar">
					<van-notice-bar custom-class="notice-bar-radius" background="transparent" color="#3c91ff"
						left-icon="volume-o" :text="notice.note" />
				</view>
			</view>
			<view class="notice-image-container">
				<van-image width="100%" height="100%" radius="60rpx" :src="noticeImage" @click="handleImageClick"
					lazy-load />
			</view>
		</view>

		<!-- 轮播图卡片 -->
		<view class="content-card">
			<swiper class="carousel" circular :indicator-dots="indicatorDots" :autoplay="autoplay" :interval="interval"
				:duration="duration">
				<swiper-item v-for="(item, index) in swiperImg" :key="index">
					<view class="carousel-item">
						<van-image width="100%" height="100%" radius="10rpx" :src="item.imagePath || ''" />
					</view>
				</swiper-item>
			</swiper>
		</view>

		<!-- 分类卡片 -->
		<view class="content-card category-card">
			<view class="category-grid">
				<view v-for="(item, index) in classify" :key="index" class="category-item" @click="onTargetMenus(item)">
					<view class="category-icon">
						<van-icon size="80rpx" :name="item.image || 'circle-o'" color="#3c91ff" />
					</view>
					<view class="category-text">{{item.name}}</view>
				</view>
			</view>
		</view>

		<!-- 新增：shops-container的背景容器 -->
		<view class="shops-background">
			<view style="background-color:#FFFFFF ; z-index: 0;">
				<!-- 深夜零食区域 -->
				<view class="shops-container">
					<view class="shops-header flex-b-c">
						<view class="flex-s-c">
							<view class="section-title">深夜零食</view>
						</view>
						<view class="building-selector-wrapper">
							<view class="building-selector" @click="toggleBuildingSelect">
								<view class="building-btn" :class="{ active: isBuildingOpen }">
									<view class="building-text">
										{{selectedBuildingText}}
										<van-icon name="arrow-down" size="20rpx" color="#3c91ff" />
									</view>
								</view>

								<view class="building-dropdown" v-show="isBuildingOpen" @click.stop>
									<view class="building-item" v-for="(item, index) in buildingOptions" :key="index"
										:class="{ active: selectedBuilding.value === item.value }"
										@click="selectBuilding(item)">
										<view class="item-icon">
											<van-icon v-if="selectedBuilding.value === item.value" name="checkmark"
												size="20rpx" color="#3c91ff" />
										</view>
										<view class="item-text">{{item.text}}</view>
									</view>
								</view>
							</view>
						</view>
					</view>

					<view class="category-tags">
						<view v-for="(tag, index) in categoryTags" :key="index" class="tag-item"
							:class="{ active: activeCategory === index }" @click="selectCategory(tag, index)">
							{{tag.categoryName}}
						</view>
					</view>

					<view class="products-grid">
						<view class="product-item" v-for="(item, index) in filteredProducts" :key="index"
							@click="handleProductClick(item)">
							<view class="product-image-container">
								<van-image width="100%" height="260rpx" radius="10rpx" :src="item.thumbnail || ''" />
								<view class="discount-tag" v-if="item.discount">{{item.discount}}</view>

								<!-- 会员价标签（右上角） -->
								<view class="vip-tag" v-if="item.vipPrice">
									<text class="tag-label">会员价</text>
									<text class="tag-price">¥{{item.vipPrice}}</text>
								</view>
							</view>
							<view class="product-info">
								<view class="product-name-line">
									<view class="product-name">{{item.productName}}</view>
									<view class="cart-quantity-container" v-if="item.cartQuantity > 0">
										<!-- 修改点：添加专门的减号按钮容器并绑定事件 -->
										<view class="decrease-button"
											@click.stop="decreaseCartItem(item, index, $event)">
											<van-icon name="minus" size="20px" color="#3c91ff" />
										</view>
										<span class="cart-quantity">{{item.cartQuantity}}</span>
									</view>
									<view class="add-to-cart-button" @click.stop="addToCart(item, index, $event)">
										<van-icon name="plus" size="20px" color="#3c91ff" />
									</view>
								</view>
								<view class="product-price">
									<text class="current-price">￥{{item.price}}</text>
									<text class="original-price"
										v-if="item.originalPrice">￥{{item.originalPrice}}</text>

									<!-- 会员价提示（下方） -->
									<view class="vip-price-info" v-if="item.vipPrice">
										<text class="vip-label">会员专享</text>
										<text class="vip-value">¥{{item.vipPrice}}</text>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

		</view>
	</view>

	<!-- 悬浮购物车 -->
	<view class="floating-cart" @click="openCart">
		<van-badge :content="cartCount" max="99">
			<van-icon name="cart-o" size="48rpx" color="#fff" />
		</van-badge>
	</view>

	<!-- 购物车数量提示1 -->
	<view class="cart-count-badge" v-if="cartCount > 0">
		{{cartCount}}
	</view>

	<!-- 添加商品动画元素 -->
	<view v-if="isAnimating" class="floating-item" :style="{
      left: startX + 'px',
      top: startY + 'px',
      opacity: animationOpacity,
      transform: `scale(${animationScale}) translate(${translateX}px, ${translateY}px)`
    }">
		<van-image width="100%" height="100%" :src="animationProductImg || ''" />
	</view>

	<!-- 添加一个透明遮罩层来捕获外部点击 -->
	<view class="dropdown-backdrop" v-if="isBuildingOpen" @click="handleDropdownOutsideClick" />
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		computed,
		nextTick,
		watch,
		onUnmounted
	} from 'vue'
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app'
	import {
		getClassify,
		getNotice,
		getSwiperImg,
		getSchoolList,
		getProductsType,
		getProductsByBuilding,
		getProductsByCategoryAndBuilding
	} from '@/api/index.js'

	// 页面基础数据
	const schoolName = ref('请选择大学')
	const classify = ref([])
	const swiperImg = ref([])
	const notice = reactive({
		title: '',
		note: ''
	})
	const isShowTip = ref(true)
	const indicatorDots = ref(true)
	const autoplay = ref(true)
	const interval = ref(3000)
	const duration = ref(500)

	// 公告栏右侧图片
	const noticeImage = ref('/static/image/weixin.png')

	// 商品分类和筛选
	const selectedBuilding = ref(0)
	const activeCategory = ref(0)
	const buildingOptions = ref([{
		text: '选择楼栋',
		value: 0
	}])
	const categoryTags = ref()
	const SELECTED_BUILDING_TEXT_KEY = 'selectedBuildingText' // 新增：楼栋名称存储键名

	// 购物车相关
	const cartCount = ref(0)
	const isAnimating = ref(false)
	const animationProductImg = ref('')
	const startX = ref(0)
	const startY = ref(0)
	const translateX = ref(0)
	const translateY = ref(0)
	const animationScale = ref(1)
	const animationOpacity = ref(1)
	let cartPosition = {
		x: 0,
		y: 0
	}
	let animationId = null

	// 本地存储键名
	const CART_STORAGE_KEY = 'shop_cart'
	const CART_QUANTITY_KEY = 'cart_quantity'

	// 购物车状态管理
	const cartState = reactive({
		items: [] // 存储购物车中的商品完整信息
	})

	// 初始化商品数据
	const initializeProducts = () => {
		return [{
				id: -1,
				productName: '卫龙香辣魔芋',
				price: '1.5',
				thumbnail: 'https://paole.hebeixiaoyu.cn/run/profile/upload/shipin1.png',
				tag: '方便速食',
				buildingId: 1,
				quantity: 10,
				checked: false,
				cartQuantity: 0,
				originalPrice: '2.0',
				vipPrice: '1.2' // 会员价格
			},
			{
				id: -1,
				productName: '好丽友果滋果心葡萄味',
				price: '3.5',
				thumbnail: 'https://paole.hebeixiaoyu.cn/run/profile/upload/shupian.png',
				tag: '奶豆乳品',
				buildingId: 2,
				quantity: 15,
				checked: false,
				cartQuantity: 0,
				originalPrice: '4.0',
				vipPrice: '3.0' // 会员价格
			}
			// {
			// 	id: -1,
			// 	productName: '健二哥怪味胡豆',
			// 	price: '5.0',
			// 	thumbnail: '/static/image/shupian.png',
			// 	originalPrice: '6.5',
			// 	tag: '方便速食',
			// 	buildingId: 3,
			// 	quantity: 8,
			// 	checked: false,
			// 	cartQuantity: 0,
			// 	vipPrice: '4.5' // 会员价格
			// },
			// {
			// 	id: 4,
			// 	productName: '可比克番茄味薯片',
			// 	price: '6.5',
			// 	thumbnail: '/static/image/shupian.png',
			// 	tag: '日常用品',
			// 	buildingId: 4,
			// 	quantity: 20,
			// 	checked: false,
			// 	cartQuantity: 0,
			// 	originalPrice: '7.5',
			// 	vipPrice: '6.0' // 会员价格
			// },
			// {
			// 	id: -1,
			// 	productName: '可口可乐',
			// 	price: '3.0',
			// 	thumbnail: '/static/image/shupian.png',
			// 	tag: '酒水饮料',
			// 	buildingId: 1,
			// 	quantity: 25,
			// 	checked: false,
			// 	cartQuantity: 0,
			// 	originalPrice: '3.5',
			// 	vipPrice: '2.8' // 会员价格
			// },
			// {
			// 	id: -1,
			// 	productName: '方便面',
			// 	price: '4.5',
			// 	thumbnail: '/static/image/shupian.png',
			// 	tag: '方便速食',
			// 	buildingId: 2,
			// 	quantity: 12,
			// 	checked: false,
			// 	cartQuantity: 0,
			// 	originalPrice: '5.0',
			// 	vipPrice: '4.0' // 会员价格
			// },
			// {
			// 	id: -1,
			// 	productName: '纯牛奶',
			// 	price: '5.0',
			// 	thumbnail: '/static/image/lunbotu1.png',
			// 	tag: '奶豆乳品',
			// 	buildingId: 3,
			// 	quantity: 18,
			// 	checked: false,
			// 	cartQuantity: 0,
			// 	originalPrice: '5.5',
			// 	vipPrice: '4.8' // 会员价格
			// },
			// {
			// 	id: -1,
			// 	productName: '卫生纸',
			// 	price: '10.0',
			// 	thumbnail: '/static/image/lunbotu1.png',
			// 	tag: '日常用品',
			// 	buildingId: 4,
			// 	quantity: 10,
			// 	checked: false,
			// 	cartQuantity: 0,
			// 	originalPrice: '12.0',
			// 	vipPrice: '9.5' // 会员价格
			// }
		]
	}

	// 商品列表
	const products = ref(initializeProducts())

	// 工具函数：获取购物车总数量
	const getCartQuantity = () => {
		try {
			const quantity = uni.getStorageSync(CART_QUANTITY_KEY);
			return quantity ? parseInt(quantity) : 0;
		} catch (error) {
			console.error('获取购物车数量失败:', error);
			return 0;
		}
	};

	// 工具函数：更新购物车总数量
	const updateCartQuantity = (newQuantity) => {
		try {
			uni.setStorageSync(CART_QUANTITY_KEY, newQuantity.toString());
			console.log('购物车总数量已更新为:', newQuantity);
			return true;
		} catch (error) {
			console.error('更新购物车数量失败:', error);
			return false;
		}
	};

	// 工具函数：计算购物车总数量
	const calculateCartQuantity = (cartList) => {
		return cartList.reduce((sum, item) => sum + item.quantity, 0);
	};

	// 计算属性：根据分类、楼栋和库存筛选商品
	const filteredProducts = computed(() => {
		const inStockProducts = products.value.filter(item => item.quantity > 0)

		if (activeCategory.value === 0 && selectedBuilding.value === 0) {
			return inStockProducts
		} else if (activeCategory.value === 0) {
			return inStockProducts.filter(item => item.buildingId === selectedBuilding.value)
		} else if (selectedBuilding.value === 0) {
			return inStockProducts.filter(item => item.tag === categoryTags[activeCategory.value])
		} else {
			return inStockProducts.filter(item =>
				item.tag === categoryTags[activeCategory.value] &&
				item.buildingId === selectedBuilding.value
			)
		}
	})

	// 从本地存储加载购物车数据
	const loadCartFromStorage = () => {
		try {
			const storedCart = uni.getStorageSync(CART_STORAGE_KEY)

			if (storedCart && storedCart.length > 0) {
				console.log('?? 从本地存储加载购物车数据:', storedCart)

				// 更新购物车状态 - 现在存储完整商品信息
				cartState.items = storedCart

				// 同步商品列表中的购物车数量
				updateProductsCartQuantity()

				// 更新购物车计数
				updateCartCount()

				// 更新购物车总数量存储
				updateCartQuantity(calculateCartQuantity(storedCart));
			} else {
				console.log('?? 本地存储中没有购物车数据')
				cartState.items = []
				resetProductsCartQuantity()
				updateCartQuantity(0);
			}
		} catch (error) {
			console.error('❌ 从本地存储加载购物车数据失败:', error)
			uni.showToast({
				title: '加载购物车数据失败',
				icon: 'none'
			})
			cartState.items = []
			resetProductsCartQuantity()
			updateCartQuantity(0);
		}
	}

	// 保存购物车数据到本地存储
	const saveCartToStorage = () => {
		try {
			// 过滤掉数量为0的商品
			const validItems = cartState.items.filter(item => item.quantity > 0)

			uni.setStorageSync(CART_STORAGE_KEY, validItems)
			console.log('✅ 购物车数据已保存到本地存储，共', validItems.length, '件商品')

			// 更新购物车总数量
			const totalQuantity = calculateCartQuantity(validItems);
			updateCartQuantity(totalQuantity);
		} catch (error) {
			console.error('❌ 保存购物车数据到本地存储失败:', error)
			uni.showToast({
				title: '购物车数据保存失败',
				icon: 'none'
			})
		}
	}

	// 更新商品列表中的购物车数量
	const updateProductsCartQuantity = () => {
		// 创建ID到购物车数量的映射
		const cartMap = new Map()
		cartState.items.forEach(item => {
			cartMap.set(item.id, item.quantity)
		})

		// 更新商品列表中的购物车数量
		products.value.forEach(product => {
			const quantity = cartMap.get(product.id) || 0
			product.cartQuantity = quantity
			product.checked = quantity > 0
		})
	}

	// 重置所有商品的购物车数量为0
	const resetProductsCartQuantity = () => {
		products.value.forEach(product => {
			product.cartQuantity = 0
			product.checked = false
		})
	}

	// 更新购物车计数
	const updateCartCount = () => {
		cartCount.value = cartState.items.reduce((sum, item) => sum + item.quantity, 0)
	}

	// 查找购物车中是否存在该商品
	const findCartItemIndex = (id) => {
		return cartState.items.findIndex(item => item.id === id)
	}

	// 更新购物车中商品数量
	const updateCartItemQuantity = (id, newQuantity) => {
		if (newQuantity < 0) return

		// 找到完整的商品信息
		const product = products.value.find(p => p.id === id)
		if (!product) return

		// 确保价格是数字类型
		product.price = parseFloat(product.price);

		// 立即更新商品列表中的数量，确保UI同步
		const productIndex = products.value.findIndex(p => p.id === id)
		if (productIndex !== -1) {
			products.value[productIndex].cartQuantity = newQuantity
		}

		// 使用Vue的响应式API更新状态，确保视图立即更新
		const index = findCartItemIndex(id)

		if (index !== -1) {
			// 商品已在购物车中
			if (newQuantity === 0) {
				// 移除商品
				cartState.items.splice(index, 1)
			} else {
				// 更新数量
				cartState.items[index].quantity = newQuantity
				// 确保购物车中的价格也是数字类型
				cartState.items[index].price = product.price;
			}
		} else if (newQuantity > 0) {
			// 添加新商品 - 现在保存完整的商品信息
			const cartItem = {
				...product,
				quantity: newQuantity,
				// 确保价格是数字类型
				price: product.price
			}
			cartState.items.push(cartItem)
		}

		// 更新购物车计数
		updateCartCount()

		// 保存到本地存储
		// 使用nextTick确保DOM更新完成后再保存，避免性能问题
		nextTick(() => {
			saveCartToStorage()
		})
	}

	// 监听购物车状态变化
	watch(() => cartState.items, (newItems, oldItems) => {
		if (JSON.stringify(newItems) !== JSON.stringify(oldItems)) {
			saveCartToStorage()
		}
	}, {
		deep: true
	})

	// 监听商品列表中购物车数量的变化
	watch(() => products.value.map(p => ({
		id: p.id,
		cartQuantity: p.cartQuantity
	})), (newValues, oldValues) => {
		if (JSON.stringify(newValues) !== JSON.stringify(oldValues)) {
			// 从商品列表同步到购物车状态
			cartState.items = []

			newValues.forEach(item => {
				if (item.cartQuantity > 0) {
					// 找到完整的商品信息
					const product = products.value.find(p => p.id === item.id)
					if (product) {
						cartState.items.push({
							...product,
							quantity: item.cartQuantity,
							// 确保价格是数字类型
							price: parseFloat(product.price)
						})
					}
				}
			})

			// 更新购物车计数
			updateCartCount()

			// 保存到本地存储
			saveCartToStorage()
		}
	}, {
		deep: true
	})

	// 页面加载时获取购物车位置并加载数据
	onMounted(() => {
		// 获取购物车位置
		const query = uni.createSelectorQuery()
		query.select('.floating-cart').boundingClientRect(rect => {
			if (rect) {
				cartPosition = {
					x: rect.left + rect.width / 2,
					y: rect.top + rect.height / 2
				}
			}
		}).exec()

		// 页面加载时立即加载购物车数据
		loadCartFromStorage()

		// 初始化商品数量为0，确保每次加载页面时都是0
		resetProductsCartQuantity()
		// 添加全局点击事件监听
		document.addEventListener('click', closeDropdownIfOpen);
	})

	// 页面卸载时移除事件监听
	onUnmounted(() => {
		// 清除动画
		if (animationId) {
			cancelAnimationFrame(animationId)
		}
		// 移除全局点击事件监听
		document.removeEventListener('click', closeDropdownIfOpen);
	})




	onShow(() => {
		// 使用 Promise.all 并行加载数据
		Promise.all([
			getClassifyItem(),
			getShangPinLeiBie(),
			getNoticeData(),
			getNoticeImage()
		]).then(() => {
			// 数据全部加载完成后再处理分类和商品
			const runDepartmentLis = uni.getStorageSync("runDepartmentList") || []
			console.log("------")
			console.log(runDepartmentLis)
			if (Array.isArray(runDepartmentLis)) {
				console.log("------")
				handleBuildingData(runDepartmentLis)
			} else {
				console.log("+++++")
				console.warn('楼栋数据格式错误，使用默认数据')
				buildingOptions.value = [{
						text: '选择楼栋',
						value: 0
					},
					{
						text: '1号楼',
						value: 1
					},
					{
						text: '2号楼',
						value: 2
					},
					{
						text: '3号楼',
						value: 3
					}
				]
			}

			// 从本地存储获取已选择的楼栋名称
			const storedBuildingText = uni.getStorageSync(SELECTED_BUILDING_TEXT_KEY);
			if (storedBuildingText) {
				selectedBuilding.value = buildingOptions.value.findIndex(item => item.text ===
						storedBuildingText) >= 0 ?
					buildingOptions.value.find(item => item.text === storedBuildingText).value : 0;
			}

			// 新增：自动选择第一个商品类别
			if (categoryTags.value && categoryTags.value.length > 0) {
				// 如果当前没有选中的分类（初始状态或未选择），或者当前选中的分类不存在了
				if (activeCategory.value === 0 || !categoryTags.value[activeCategory.value - 1]) {
					// 设置第一个分类为选中状态
					activeCategory.value = 0;

					// 如果已经选择了楼栋，则加载对应数据
					if (selectedBuilding.value !== 0) {
						const firstCategory = categoryTags.value[0];
						if (firstCategory) {
							selectCategory(firstCategory, 0);
						}
					}
				} else {
					// 如果有选中的分类，重新加载该分类数据
					const currentCategory = categoryTags.value[activeCategory.value - 1];
					if (currentCategory && selectedBuilding.value !== 0) {
						selectCategory(currentCategory, activeCategory.value - 1);
					}
				}
			}
		}).catch(error => {
			console.error('数据加载失败:', error);
		});

		// 单独处理购物车数据
		const token = uni.getStorageSync("token")
		if (token) {
			getSchoolLists()
		}

		// 页面显示时重新加载购物车数据并同步数量
		loadCartFromStorage()
		updateProductsCartQuantity()
	})

	// 获取分类和轮播图数据
	const getClassifyItem = async () => {
		try {
			const res = await getClassify()
			classify.value = res.data.runCategoryList || []
			swiperImg.value = res.data.runCarouselList || []

			if (swiperImg.value && swiperImg.value.length > 0) {
				swiperImg.value.forEach(item => {
					if (!item.imagePath) {
						item.imagePath = ''
					}
				})
			}
		} catch (e) {
			console.log(e)
		}
	}

	// 获取公告数据
	const getNoticeData = async () => {
		try {
			const res = await getNotice()
			notice.note = res.data || '暂无公告'
		} catch (e) {
			console.log('获取公告失败', e)
			notice.note = '加载中...'
		}
	}

	// 修改全局点击事件监听函数
	const closeDropdownIfOpen = (event) => {
		// 如果下拉菜单是打开的
		if (isBuildingOpen.value) {
			// 使用 setTimeout 延迟检查，确保事件处理完成
			setTimeout(() => {
				// 检查点击是否发生在下拉菜单内部
				const dropdownElement = document.querySelector('.building-dropdown');
				const buildingButton = document.querySelector('.building-btn');

				// 如果点击发生在下拉菜单或按钮外部，则关闭下拉菜单
				if (!dropdownElement || !dropdownElement.contains(event.target)) {
					if (!buildingButton || !buildingButton.contains(event.target)) {
						isBuildingOpen.value = false;
					}
				}
			}, 0);
		}
	};
	// 获取商品类别
	const getShangPinLeiBie = async () => {
		try {
			const res = await getProductsType()
			console.log(res)
			categoryTags.value = res.data || []
			uni.setStorageSync('classify', categoryTags.value)
		} catch (e) {
			console.log('获取公告失败', e)
			notice.note = '加载中...'
		}
	}

	// 获取公告栏右侧图片
	const getNoticeImage = async () => {
		try {
			noticeImage.value = '/static/image/weixin.png'
		} catch (e) {
			console.log('获取公告图片失败', e)
			noticeImage.value = '/static/image/default_notice.png'
		}
	}

	// 动态处理楼栋数据
	const handleBuildingData = (departments) => {
		const validDepartments = departments.filter(item => item.id !== null && item.name !== null)
		buildingOptions.value = [{
				text: '选择楼栋',
				value: 0
			},
			...validDepartments.map(item => ({
				text: item.name,
				value: item.id
			}))
		]
	}

	// 楼栋选择器状态
	const isBuildingOpen = ref(false)
	const selectedBuildingText = computed(() => {
		const selectedItem = buildingOptions.value.find(item => item.value === selectedBuilding.value)
		return selectedItem ? selectedItem.text : '全部楼栋'
	})

	// 切换楼栋选择器显示状态
	const toggleBuildingSelect = () => {
		isBuildingOpen.value = !isBuildingOpen.value
	}

	// 处理下拉菜单外部点击
	const handleDropdownOutsideClick = () => {
		isBuildingOpen.value = false
	}

	const selectBuilding = async (item) => {
		selectedBuilding.value = item.value;
		// 将楼栋存储在本地存储当中
		uni.setStorageSync("selectedBuilding", selectedBuilding.value);
		console.log(uni.getStorageSync("selectedBuilding"));
		uni.setStorageSync(SELECTED_BUILDING_TEXT_KEY, item.text); // 存储楼栋名称

		isBuildingOpen.value = false; // 关闭下拉菜单

		try {
			const res = await getProductsByBuilding(item.value);

			// 保存当前购物车状态
			const cartStateSnapshot = JSON.parse(JSON.stringify(cartState.items));

			// 更新商品列表
			products.value = res.data || [];

			// 恢复购物车状态
			updateProductsCartQuantity();

			// 从商品列表同步到购物车状态
			cartState.items = [];
			products.value.forEach(product => {
				if (product.cartQuantity > 0) {
					cartState.items.push({
						id: product.id,
						quantity: product.cartQuantity,
						// 确保价格是数字类型
						price: parseFloat(product.price)
					});
				}
			});

			// 更新购物车计数
			updateCartCount();


		} catch (error) {
			console.error('获取楼栋商品失败:', error);
			uni.showToast({
				title: '加载商品失败，请重试',
				icon: 'none'
			});
		}
	};

	// 选择学校
	const selectSchool = () => {
		const data = uni.getStorageSync('login_data')
		if (!data) {
			uni.showModal({
				title: '登录提示',
				content: '请先登录后再进行操作',
				confirmText: '去登录',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						uni.switchTab({
							url: '/pages/mine/mine'
						})
					}
				}
			})
		} else {
			uni.navigateTo({
				url: '/package/pages/selectSchool/selectSchool'
			})
		}
	}

	// 处理公告栏图片点击
	const handleImageClick = () => {
		console.log('公告栏图片被点击')
		// 这里可以添加图片点击后的逻辑
		uni.navigateTo({
			url: '/package/pages/guanli/guanli'
		})
	}

	// 添加商品点击跳转逻辑
	const handleProductClick = (item) => {
		const schoolId = uni.getStorageSync('school_id')
		const token = uni.getStorageSync('token')

		if (!item.id) {
			console.warn('商品缺少 ID，无法跳转')
			return
		}

		if (item.id === -1 && !token) {
			uni.showModal({
				title: '登录提示',
				content: '请先登录后再进行操作',
				success: (res) => {
					if (res.confirm) {
						uni.switchTab({
							url: '/pages/mine/mine'
						})
					}
				}
			})
			return
		}

		if (item.id === -1 && !schoolId) {
			uni.showModal({
				title: '提示',
				content: '请先选择学校后再进行操作'
			})
			return
		}

		if (selectedBuilding.value === 0) {
			uni.showModal({
				title: '提示',
				content: '请先选择楼栋后再进行操作'
			})
			return
		}

		uni.setStorageSync('shangPinId', item.id)

		uni.navigateTo({
			url: `/package/pages/skuxiangqing/skuxiangqing`,
			success: () => {
				console.log(`跳转到商品详情页，ID：${item.id}`)
			},
			fail: (err) => {
				console.error('跳转失败', err)
			}
		})
	}

	const getSchoolLists = () => {
		console.log('开始获取学校信息')

		let storedSchoolName = uni.getStorageSync("school_name")
		const schoolId = uni.getStorageSync('school_id')

		console.log('存储的学校名称:', storedSchoolName)
		console.log('存储的学校ID:', schoolId)

		if (storedSchoolName) {
			schoolName.value = storedSchoolName
		} else if (schoolId) {
			console.log('通过API获取学校信息，ID:', schoolId)
		} else {
			schoolName.value = '请选择大学'
		}

		console.log('最终学校名称:', schoolName.value)
	}

	// 导航到目标菜单页面
	const onTargetMenus = (item) => {


		const data = uni.getStorageSync('login_data')
		if (!data) {
			uni.showModal({
				title: '登录提示',
				content: '请先登录后再进行操作',
				confirmText: '去登录',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						uni.switchTab({
							url: '/pages/mine/mine'
						})
					}
				}
			})
			return;
		}
		const schoolId = uni.getStorageSync('school_id');

		if (!schoolId) {
			uni.showModal({
				title: '提示',
				content: '请先选择学校后再进行操作',
				showCancel: false,
				confirmText: '去选择',
				success: ({
					confirm
				}) => {
					if (confirm) {
						uni.navigateTo({
							url: '/package/pages/selectSchool/selectSchool'
						});
					}
				}
			});
			return;
		}




		// 原有逻辑保持不变
		if (item.url === '/package/pages/ShopPage/ShopPage') {
			console.log(selectedBuilding.value)
			if (selectedBuilding.value === 0) {
				uni.showToast({
					title: '请先选择楼栋后再进行操作',
					icon: 'none'
				});
			} else {
				uni.navigateTo({
					url: `${item.url}?name=${item.name}&cid=${item.id}`
				});
			}
		} else {
			uni.navigateTo({
				url: `${item.url}?name=${item.name}&cid=${item.id}`
			});
		}
	}

	// 分类标签选择
	const selectCategory = async (tag, index) => {
		console.log(tag.id)
		console.log("88888888888888")
		const schoolId = uni.getStorageSync('school_id')
		const token = uni.getStorageSync('token')

		if (!token) {
			uni.showModal({
				title: '登录提示',
				content: '请先登录后再进行操作',
				success: (res) => {
					if (res.confirm) {
						uni.switchTab({
							url: '/pages/mine/mine'
						})
					}
				}
			})
			return
		}

		if (!schoolId) {
			uni.showModal({
				title: '提示',
				content: '请先选择学校后再进行操作'
			})
			return
		}

		if (selectedBuilding.value === 0) {
			uni.showModal({
				title: '提示',
				content: '请先选择楼栋后再进行操作'
			})
			return
		}

		const params = {
			categoryId: tag.id,
			buildingId: selectedBuilding.value
		};

		try {
			const response = await getProductsByCategoryAndBuilding(params);

			if (response.code === 200 && response.data) {
				// 所有条件满足后，标记当前类别为选中状态
				activeCategory.value = index
				console.log("选中状态" + activeCategory.value)
				// 保存当前购物车状态
				const cartStateSnapshot = JSON.parse(JSON.stringify(cartState.items))

				// 更新商品列表，保持与选择楼栋时一致的格式
				products.value = response.data.map(product => ({
					...product,
					cartQuantity: 0,
					checked: false
				}))

				// 恢复购物车状态
				updateProductsCartQuantity()

				// 从商品列表同步到购物车状态
				cartState.items = []
				products.value.forEach(product => {
					if (product.cartQuantity > 0) {
						cartState.items.push({
							id: product.id,
							quantity: product.cartQuantity,
							price: parseFloat(product.price)
						})
					}
				})

				// 更新购物车计数
				updateCartCount()

				// 显示成功提示
				// uni.showToast({
				// 	title: `已加载${tag.categoryName}商品`,
				// 	icon: 'success'
				// })
			} else {
				// 显示失败提示
				// uni.showToast({
				// 	title: '加载商品失败',
				// 	icon: 'none'
				// })
			}
		} catch (error) {
			console.error('获取商品数据失败:', error)
			uni.showToast({
				title: '网络错误，请重试',
				icon: 'none'
			})
		}
	}

	// 打开购物车
	const openCart = () => {
		uni.navigateTo({
			url: '/package/pages/ShopPage/ShopPage'
		})
	}

	// 添加商品到购物车
	const addToCart = (item, index, event) => {
		event.stopPropagation() // 确保事件不会冒泡

		const schoolId = uni.getStorageSync('school_id')
		const token = uni.getStorageSync('token')

		if (!token) {
			uni.showToast({
				title: '请先登录后再进行操作',
				icon: 'none'
			})
			return
		}

		if (!schoolId) {
			uni.showToast({
				title: '请先选择学校后再进行操作',
				icon: 'none'
			})
			return
		}

		if (selectedBuilding.value === 0) {
			uni.showToast({
				title: '请先选择楼栋后再进行操作',
				icon: 'none'
			})
			return
		}

		// 检查商品库存
		if (item.quantity <= 0) {
			uni.showToast({
				title: '商品已售罄',
				icon: 'none'
			})
			return
		}

		// 立即更新商品数量，确保UI响应
		item.cartQuantity += 1

		// 更新购物车中商品数量
		updateCartItemQuantity(item.id, item.cartQuantity)

		// 开始添加商品动画
		startAddToCartAnimation(event, item.img)
	}

	// 减少购物车中商品数量
	const decreaseCartItem = (item, index, event) => {
		// 确保事件不会冒泡到商品卡片上
		if (event) {
			event.stopPropagation()
		}

		if (item.cartQuantity > 0) {
			// 立即更新商品数量，确保UI响应
			item.cartQuantity -= 1

			// 更新购物车中商品数量
			updateCartItemQuantity(item.id, item.cartQuantity)
		}
	}

	// 开始添加商品动画
	const startAddToCartAnimation = (event, imgUrl) => {
		if (!event || !imgUrl) return

		// 获取点击元素的位置
		const button = event.currentTarget || event.target

		// 使用更可靠的方式获取元素位置
		const query = uni.createSelectorQuery()
		query.select(`#add-btn-${button.dataset.index}`).boundingClientRect(rect => {
			if (!rect) return

			// 设置动画起始位置
			startX.value = rect.left
			startY.value = rect.top

			// 设置动画图片
			animationProductImg.value = imgUrl

			// 显示动画元素
			isAnimating.value = true

			// 计算动画路径
			const dx = cartPosition.x - startX.value
			const dy = cartPosition.y - startY.value

			// 动画持续时间（毫秒）
			const duration = 800
			const startTime = Date.now()

			// 动画函数
			const animate = () => {
				const elapsed = Date.now() - startTime
				const progress = Math.min(elapsed / duration, 1)

				// 使用缓动函数使动画更自然
				const easeOutQuad = t => t * (2 - t)
				const easeOutCirc = t => Math.sqrt(1 - Math.pow(t - 1, 4))

				// 更新动画属性
				translateX.value = dx * easeOutQuad(progress)
				translateY.value = dy * easeOutCirc(progress)
				animationScale.value = 1 - 0.7 * progress
				animationOpacity.value = 1 - progress

				// 继续动画或结束
				if (progress < 1) {
					animationId = requestAnimationFrame(animate)
				} else {
					// 动画结束
					isAnimating.value = false
					animationProductImg.value = ''
				}
			}

			// 开始动画
			animationId = requestAnimationFrame(animate)
		}).exec()
	}
</script>
<style scoped>
	/* pages/index/index.wxss */
	/* 隐藏自定义导航栏底部的边框线 */
	.ppl-navbar {
		border-bottom: none !important;
		box-shadow: none !important;
		/* 若有阴影效果也一并移除 */
	}

	/* 装饰性背景（不影响布局） */
	.decorative-bg {
		position: fixed;
		/* top: 0; */
		left: 0;
		width: 100%;
		height: 395rpx;
		background: linear-gradient(180deg, #3c91ff 25%, #e3eeff 100%);
		border-radius: 0 0 50% 50% / 0 0 15% 15%;
		z-index: 0;
		pointer-events: none;
	}

	/* 页面内容容器 */
	.page-wrapper {
		position: relative;
		z-index: 1;
		padding: 20rpx 30rpx;
		background: transparent;
	}

	/* 公告栏和图片的组合容器 */
	.notice-and-image-container {
		display: flex;
		align-items: center;
		margin: 20rpx 0;
		z-index: 5;
		position: relative;
	}

	/* 调整公告栏样式 */
	.notice-bar-wrapper {
		margin: 0;
		flex: 1;
		/* 占据剩余空间 */
	}

	.custom-notice-bar {
		width: 100%;
		/* 宽度占满父容器 */
		height: 80rpx;
		/* 设置高度与图片一致 */
	}

	/* 调整图片容器样式 */
	.notice-image-container {
		width: 80rpx;
		/* 图片宽度 */
		height: 80rpx;
		/* 图片高度 */
		margin-left: 15rpx;
		/* 与公告栏的间距 */
		border-radius: 50%;
		/* 圆形图片 */
		overflow: hidden;
		flex-shrink: 0;
		/* 防止图片被压缩 */
	}

	/* 内容卡片通用样式 */
	.content-card {
		background-color: #fff;
		border-radius: 24rpx;
		box-shadow: 0 15rpx 30rpx rgba(60, 145, 255, 0.1);
		/* padding: 30rpx; */
		margin-top: 20rpx;
		position: relative;
		z-index: 10;
	}

	/* 分类卡片样式优化 */
	.category-card {
		padding: 30rpx 15rpx;
	}

	.category-grid {
		display: grid;
		grid-template-columns: repeat(5, 1fr);
		gap: 15rpx;
	}

	.category-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 12rpx 0;
		transition: transform 0.2s;
	}

	.category-item:hover {
		transform: translateY(-5rpx);
	}

	.category-icon {
		width: 80rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 8rpx;
	}

	.category-text {
		font-size: 22rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		max-width: 100%;
		text-align: center;
	}

	/* 轮播图样式 */
	.carousel {
		height: 300rpx;
	}

	.carousel-item {
		display: block;
		height: 100%;
		line-height: 100%;
		text-align: center;
	}

	/* 校区选择器样式 */
	.nav-left {
		display: flex;
		align-items: center;
		padding-left: 20rpx;
	}

	.position-icon {
		cursor: pointer;
	}

	.location-icon-wrapper {
		margin-right: 10rpx;
	}

	.school-name-container {
		max-width: 200rpx;
	}

	.school-name {
		color: white;
		font-size: 26rpx;
		font-weight: 500;
	}

	/* 深夜零食区域样式 */
	.shops-container {
		background: linear-gradient(180deg, #DDECFF 35%, #ffffff 70%);
		background-size: 100% 200rpx;
		background-repeat: no-repeat;
		border-radius: 20rpx;
		padding: 20rpx;
		margin-top: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.shops-header {
		margin-bottom: 10rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		padding-left: 12rpx;
	}


	/* 楼栋选择器样式 */
	.building-selector-wrapper {
		position: relative;
		width: 240rpx;
	}

	.building-btn {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 12rpx 16rpx;
		border-radius: 28rpx;
		box-shadow: 0 2rpx 8rpx rgba(60, 145, 255, 0.1);
		cursor: pointer;
		transition: all 0.3s;
	}

	.building-btn.active {
		box-shadow: 0 4rpx 12rpx rgba(60, 145, 255, 0.2);
	}

	.building-text {
		font-size: 26rpx;
		color: #333;
		display: flex;
		align-items: center;
	}

	.building-dropdown {
		position: absolute;
		top: 100%;
		right: 0;
		width: 100%;
		max-height: 400rpx;
		overflow-y: auto;
		background: #FFFFFF;
		border-radius: 16rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
		padding: 8rpx 0;
		margin-top: 12rpx;
		z-index: 999;
	}

	.building-item {
		padding: 14rpx 24rpx;
		font-size: 24rpx;
		color: #666;
		display: flex;
		align-items: center;
		gap: 12rpx;
		height: 80rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.building-item.active {
		color: #3c91ff;
		font-weight: 500;
	}

	.item-icon {
		color: #3c91ff;
		font-size: 28rpx;
	}

	/* 商品分类标签样式 */
	.category-tags {
		display: flex;
		flex-wrap: wrap;
		padding: 15rpx 0;
		margin-bottom: 15rpx;
	}

	.tag-item {
		margin-right: 15rpx;
		margin-bottom: 15rpx;
		padding: 0 25rpx;
		height: 50rpx;
		line-height: 50rpx;
		border-radius: 25rpx;
		font-size: 24rpx;
		color: #333;
		background-color: transparent;
		transition: all 0.3s;
	}

	.tag-item.active {
		color: #ffd700;
		border: 1px solid #ffd700;
		background-color: transparent;
	}

	/* 商品网格布局 */
	.products-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 20rpx;
	}

	.product-item {
		background: #ffffff;
		border-radius: 15rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.product-image-container {
		position: relative;
		height: 260rpx;
	}

	.discount-tag {
		position: absolute;
		top: 10rpx;
		right: 10rpx;
		background-color: #FF5A5F;
		color: white;
		padding: 4rpx 12rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
	}

	/* 新增：会员价标签样式 */
	.vip-tag {
		position: absolute;
		top: 10rpx;
		right: 10rpx;
		background-color: #FFF3CD;
		color: #FF9800;
		padding: 4rpx 12rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		z-index: 1;
	}

	.tag-label {
		font-weight: bold;
	}

	.tag-price {
		font-weight: bold;
	}

	.product-info {
		padding: 15rpx;
	}

	.product-name-line {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 8rpx;
	}

	.product-name {
		font-size: 24rpx;
		font-weight: 500;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		flex: 1;
	}

	.cart-quantity-container {
		display: flex;
		align-items: center;
		gap: 8rpx;
	}

	.cart-quantity {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		width: 40rpx;
		height: 40rpx;
		background-color: #f5f5f5;
		border-radius: 4rpx;
		font-size: 24rpx;
	}

	.product-price {
		display: flex;
		align-items: center;
		margin-bottom: 8rpx;
	}

	.current-price {
		color: #FF5A5F;
		font-size: 28rpx;
		font-weight: bold;
	}

	.original-price {
		color: #999;
		font-size: 20rpx;
		text-decoration: line-through;
		margin-left: 10rpx;
	}

	/* 新增：会员价提示样式 */
	.vip-price-info {
		display: flex;
		align-items: center;
		background-color: #FFF3CD;
		padding: 4rpx 10rpx;
		border-radius: 4rpx;
		margin-left: 10rpx;
	}

	.vip-label {
		color: #FF9800;
		font-size: 20rpx;
		margin-right: 5rpx;
	}

	.vip-value {
		color: #FF9800;
		font-size: 24rpx;
		font-weight: bold;
	}

	.product-tag {
		display: inline-block;
		background-color: #E3EEFF;
		color: #3c91ff;
		padding: 3rpx 10rpx;
		border-radius: 4rpx;
		font-size: 20rpx;
	}

	/* 悬浮购物车样式 */
	.floating-cart {
		position: fixed;
		bottom: 100rpx;
		right: 30rpx;
		z-index: 100;
		width: 80rpx;
		height: 80rpx;
		background-color: #3c91ff;
		border-radius: 50%;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* 购物车数字提示 */
	.cart-count-badge {
		position: fixed;
		bottom: 160rpx;
		right: 20rpx;
		z-index: 101;
		width: 40rpx;
		height: 40rpx;
		background-color: #FF5A5F;
		color: white;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
	}

	/* 添加商品动画元素 */
	.floating-item {
		position: fixed;
		z-index: 200;
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		overflow: hidden;
		box-shadow: 0 6rpx 24rpx rgba(0, 0, 0, 0.3);
		pointer-events: none;
		transform-origin: center;

		transition: transform 1.2s cubic-bezier(0.25, 0.46, 0.45, 0.94),
			opacity 1.2s cubic-bezier(0.25, 0.46, 0.45, 0.94),
			left 1.2s cubic-bezier(0.25, 0.46, 0.45, 0.94),
			top 1.2s cubic-bezier(0.25, 0.46, 0.45, 0.94);
	}

	/* 购物车抖动动画 */
	@keyframes shake {

		0%,
		100% {
			transform: translateX(0);
		}

		20%,
		60% {
			transform: translateX(-12rpx);
		}

		40%,
		80% {
			transform: translateX(12rpx);
		}
	}

	.shake {
		animation: shake 0.4s ease-in-out;
	}

	/* 自定义公告栏容器 */
	.custom-notice-bar {
		background-color: rgba(227, 238, 255, 0.75);
		/* 半透明背景 */
		border-radius: 60rpx;
		/* 圆角 */
		box-shadow: 0 4rpx 12rpx rgba(60, 145, 255, 0.15);
		/* 阴影 */
		overflow: hidden;
		/* 确保内容在圆角内 */

		/* 使用Flex布局 */
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0;
	}

	/* 调整通知栏内容样式 */
	.notice-bar-radius {
		padding: 0 !important;
		/* 移除原有内边距 */
		margin: 0 16rpx;
		/* 左右边距 */
		flex: 1;
		/* 占据剩余空间 */
	}

	/* 确保图标和文字不透明 */
	.notice-bar-radius .van-notice-bar__content,
	.notice-bar-radius .van-icon {
		opacity: 1 !important;
	}

	/* 调整图标位置 */
	.notice-bar-radius .van-icon {
		margin-right: 10rpx;
	}


	/* 添加或修改以下CSS样式 */
	.building-dropdown {
		position: absolute;
		top: 100%;
		/* 显示在按钮下方 */
		left: 0;
		width: 100%;
		max-height: 200px;
		/* 设置最大高度，超过此高度将显示滚动条 */
		overflow-y: auto;
		/* 启用垂直滚动 */
		overflow-x: hidden;
		/* 禁用水平滚动 */
		background-color: white;
		border: 1px solid #e4e4e4;
		border-radius: 4px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		z-index: 1000;
		margin-top: 4px;
	}

	.dropdown-item {
		padding: 8px 12px;
		cursor: pointer;
		transition: background-color 0.2s;
	}

	.dropdown-item:hover {
		background-color: #f5f5f5;
	}
</style>